/**
 * 注册校验
 * @authors gaocc 
 * @date    2014-09-22 12:10:42
 * @for email_bound.jsp
 */
var BSTYUN = BSTYUN || {};
/*BSTYUN.dialog = {
	    close: function (id) {
	        var i,list = $.dialog.list;
	        if(id){
	            list[id].close();
	        }else{
	            for (i in list) {
	                list[i].close();
	            }
	        }
	    },
	    creat: function (options) {
	        var dialog = null;
	        options = $.extend({
	            fixed:true,
	            title:false,
	            lock:true,
	            padding:'20px 40px',
	            id: '',
	            content: ''
	        },options);
	        dialog=$.dialog(options);
	        return dialog;
	    },
	    success: function (html,time) {
	        var dialog = null;
	        time = time || 2;
	        this.close();
	        html = '<div class="success-tip"><i class="iconfont">&#379;</i>'+html+'</div>'
	        dialog = this.creat({id:'success',content:html,lock:false});
	        setTimeout(function(){
	            var $dg = $(dialog.DOM.wrap);
	            $dg.animate({'top':'-=50px','opacity':0},300,'easeInBack',function(){
	                dialog.close();
	            });
	        }, time*1000);
	    },
	    warn: function (html,callback){
	        var dialog = null;
	        html = '<div class="warn-tip"><i class="iconfont">&#227;</i>'+html+'</div>';
	        dialog = this.creat({id:'warn',content:html});
	        dialog.button({
	            name: '知道了',
	            focus: true,
	            callback: callback
	        });
	    },
	    ok: function (html,callback){
	        var dialog = null;
	        html = '<div class="ok-tip"><i class="iconfont">&#379;</i>'+html+'</div>';
	        dialog = this.creat({id:'ok',content:html});
	        dialog.button({
	            name: '知道了',
	            focus: true,
	            callback: callback
	        });
	    },
	    confirm: function (html,callback) {
	        var dialog = null;
	        html = '<div class="confirm-tip"><i class="iconfont">&#228;</i>'+html+'</div>';
	        dialog = this.creat({id:'confirm',content:html});
	        dialog.button({
	            name: '确定',
	            focus: true,
	            callback: callback
	        },{
	            name: '取消'
	        });
	    }
	};*/
BSTYUN.check = {
    //IE6判定
    isIE6: window.VBArray && !window.XMLHttpRequest,
    //判断是否为中英文，数字，下划线，减号
    isNick: function(str) {
        var nickReg = /^[\u4e00-\u9fa5A-Za-z0-9-_]+$/;
        return nickReg.test(str);
    },
    //判断邮箱
    isEmail: function(str) {
        var emailReg = /^[a-z0-9][\w\.]*@([a-z0-9][a-z0-9-]*\.)+[a-z]{2,5}$/i;
        return emailReg.test(str);
    },
    //判断手机.
    isMobile: function(str) {
        var mobileReg = /^1[345678][0-9]{9}$/;
        return mobileReg.test(str);
    },
    // 判断固话
    isTelephone: function(str) {
        var phoneReg = /^0\d{2,3}-\d{5,9}$/;
        return phoneReg.test(str);
    },
    //判断URL
    isUrl: function(str) {
        var urlReg = /^http:\/\/([\w-]+\.)+[\w-]+(\/[\w-.\/?%&=]*)?$/;
        return urlReg.test(str);
    },
    //判断数字
    isNum: function(str) {
        var numReg = /^[0-9]\d*$/;
        return numReg.test(str);
    }
};
var emailFlag;
BSTYUN.emailBound = {
    $inputs: null,
    flag: {userTel: false, vftn_code: false},
    _timer: null,/*全局定时器*/
    init:function() {
        var that = this;
        emailFlag = $("#emailFlag").val();
        /*获取input元素*/
        that.$inputs = $('.input_box').find('input');
        /*检测信息*/
        that.checkInfor();
        /*发送邮箱验证码*/
        that.sendEmailCode();
        /*提交绑定/解绑邮箱*/
        that.submitEmailBound();
        /*图片验证码替换*/
//        that.changePicCode();
    },
    checkInfor:function() {
        var that = this;
        /*获取焦点，清空错误信息*/
        that.$inputs.on('focus', function(event) {
            that.clearErrorMsg($(this));
            /*失去焦点，检测信息正确性*/
        }).on('blur', function(event) {
            var $this = $(this),
                typename = $this.attr('name'),
                val = $.trim($this.val());
            /*输入内容为空，则提示不能为空*/
            if(val == '' || val.length == 0){
                that.addErrorMsg($this,'不能为空');
                return false;
            }
            if (typename == 'userEmail') {
            	var $send = $('#getvftn_code');
                if (!BSTYUN.check.isEmail(val)) {
                    that.addErrorMsg($this,'邮箱格式不正确');
                }else{
                	if(emailFlag=="unBoundTel"){
                		$.ajax({
                            type: "post",
                            url: "/user/bound/boundEmail?random="+Math.random(),
                            data: {boundEmail:val},
                            async:false,
                            success: function(data){
                              if(data==false){
                            	  that.clearErrorMsg($this);
                            	  $send.removeClass("disabled");
                              }else{
                            	  that.addErrorMsg($this,"该邮箱未绑定");
                                  $send.addClass("disabled");
                            	 
                              }
                           }
                        });
                	}else{
                		$.ajax({
                            type: "post",
                            url: "/user/bound/boundEmail?random="+Math.random(),
                            data: {boundEmail:val},
                            async:false,
                            success: function(data){
                              if(data==false){
                                  that.addErrorMsg($this,"该邮箱已被绑定");
                                  $send.addClass("disabled");
                              }else{
                            	  that.clearErrorMsg($this);
                            	  $send.removeClass("disabled");
                              }
                           }
                        });
                	}
                	
                }
            }
        });
        /*判断邮箱，是否可以发送邮箱验证码*/
        that.$inputs.filter("[name='userEmail']").on('keyup', function(event) {
            var $send = $('#getvftn_code'),
            	$this = $(this),
                val = $.trim($this.val());
            //if(BSTYUN.register._timer != null){return false;};
            if (!BSTYUN.check.isEmail(val)) {
                $send.addClass('disabled');
            }else{
            	/*存在倒计时，清空倒计时*/
//                if(that._timer != null){
//                	$("#getvftn_code").removeClass('disabled').text('获取免费短信验证码');
//                	clearInterval(that._timer);
//                }
                $send.removeClass('disabled');
                /*判断邮箱，是否已经被注册*/
                if(emailFlag=="unBoundTel"){
            		$.ajax({
                        type: "post",
                        url: "/user/bound/boundEmail?random="+Math.random(),
                        data: {boundEmail:val},
                        async:false,
                        success: function(data){
                          if(data==false){
                        	  that.clearErrorMsg($this);
                        	  $send.removeClass("disabled");
                          }else{
                        	  that.addErrorMsg($this,"该邮箱未绑定");
                              $send.addClass("disabled");
                        	 
                          }
                       }
                    });
            	}else{
            		  $.ajax({
                          type: "post",
                          url: "/user/bound/boundEmail?random="+Math.random(),
                          data: {boundEmail:val},
                          async:false,
                          success: function(data){
                            if(data==false){
                                that.addErrorMsg($this,"该邮箱已被绑定");
                                $send.addClass("disabled");
                            }else{
                          	  that.clearErrorMsg($this);
                          	  $send.removeClass("disabled");
                            }
                         }
                      });
            	}
            }
        });
    },
    sendEmailCode: function(argument) {
        var that = this,
            $send = $('#getvftn_code'),
            $phone = that.$inputs.eq(0),
            val = null;
        var currentWay = null;
            $send.on('click', function(event) {
                var $this = $(this);
                if (!$this.hasClass('disabled')) {
                    $this.addClass('disabled');
                    val = $.trim($phone.val());
                    //判断邮箱绑定还是解绑
                    switch (emailFlag) {
    				case "emailSet":
    					currentWay = "bound";
    					messge = "邮箱绑定成功"
    					break;
    				case "emailChange":
    					currentWay = "bound";
    					messge = "邮箱绑定成功"
    					break;
    				case "unBoundTel":
    					currentWay = "unBound";
    					messge = "手机解绑成功"
    					break;					
    				default:
    					break;
    				}
                    /*发送ajax请求短信验证码*/
                    $.ajax({
                        type: "post",
                        url: "/user/sendInfoByAccount?random="+Math.random(),
                        //url: "text.txt?random="+Math.random(),
                        data: {account:val,flag:currentWay},
                        success: function(data){
                        	/*发送邮件 0:发送成功 1：发送失败 */
                            var success = data.flag;
                            if(success=="1"){
                                that.addErrorMsg($phone,'邮件发送失败，请重试！');
                                $this.removeClass('disabled').text('获取验证码');
                                return false;
                            }else{
                                that.addTipMsg($phone,'邮件发送成功');
                                $this.removeClass('disabled').text('获取验证码');
                                /*倒计时重发*/
//                                var i = 60;
//                                clearInterval(that._timer);
//                                that._timer = setInterval(function() {
//                                    if (i == 0) {
//                                        clearInterval(that._timer);
//                                        that._timer = null;
//                                        $this.removeClass('disabled').text('获取验证码');
//                                    } else {
//                                        i--;
//                                        $this.text('再次发送验证码(' + i + ')');
//                                    }
//                                }, 1000);
                            }
                        }
                    });
                }else{
                   /*禁止状态，不能点击*/
                   return false;
                };
            });
    },
    submitEmailBound:function() {
        var that = this,
            $submit = $("#go2register");
        $submit.on('click', function(event) {
            var flag = that.flag,
                data = {};
            $.each(that.$inputs, function(index, val) {
                 $(this).trigger('blur');
            });
            if (flag.userTel != false&&flag.vftn_code!=false) {
            	data.account = $.trim(that.$inputs.eq(0).val()),
            	data.messageCode = $.trim(that.$inputs.eq(1).val()),
            	data.emailFlag = emailFlag;
                $.ajax({
                    type: "POST",
                    url : "/user/safeInfoBound?random="+Math.random(),
                    data: data,
                    async: true,
                    error: function(request) {
                    	BSTYUN.dialog.ok('服务器繁忙，请稍后尝试')
                        return false;
                    },
                    success: function(data) {
                    	//0:验证码错误 1：绑定成功 2：绑定失败
                    	 switch (emailFlag) {
         				case "emailSet":
         					currentWay = "bound";
         					message = "邮箱绑定成功"
         					break;
         				case "emailChange":
         					currentWay = "bound";
         					message = "邮箱绑定成功"
         					break;
         				case "unBoundTel":
         					currentWay = "unBound";
         					message = "手机解绑成功"
         					break;					
         				default:
         					break;
         				}
                        if(data.message=='1'){
                        	BSTYUN.dialog.ok(messge,function(){
                        		window.location.href = "/user/userCenter/memberSafetyInfo"
                        	})
                        }else if(data.message=='0'){
                            that.addErrorMsg(that.$inputs.filter("[name='vftn_code']"),'邮件验证码错误！');
                            return false;
                        }else if(data.message=='2'){
                        	if(emailFlag=="unBoundTel"){
                        		BSTYUN.dialog.warn("解绑失败");
                        	}else{
                        		BSTYUN.dialog.warn("绑定失败");
                        	}
                        	return false;
                        }
                    }
                });
            };
            return false;
        });
    },
//    changePicCode:function() {
//        var $change = $("#changeImgCode"),
//            $img = $change.prev();
//        $change.on('click', function(event) {
//            $img.attr('src','/image/code?random='+Math.random());
//        });
//    },
    /*清空$this的错误提示信息*/
    clearErrorMsg:function($this) {
        var $this = $this,
            that = this,
            typename = $this.attr('name');
        if (typename == 'userEmail') {
            that.flag.userTel = true;
            $this.parent().next().next().children('.error_msg').remove();
        }else if(typename == 'vftn_code'){
        	that.flag.vftn_code = true;
            $this.next().remove();
        } 
    },
    /*显示错误信息*/
    addErrorMsg:function ($this,msg) {
        var $this = $this,
            that = this,
            typename = $this.attr('name');
        if (typename == 'userEmail') {
            that.flag.userTel = false;
            $this.parent().next().next().html('<span class="error_msg">'+msg+'</span>');
        }else if (typename == 'vftn_code') {
            that.flag.vftn_code = false;
            if($this.next('.error_msg').size() != 0){
                $this.next('.error_msg').html(msg);
            }else{
                $this.after('<span class="error_msg">'+msg+'</span>');
            }
        }
    },
    /*显示提示信息*/
    addTipMsg:function ($this,msg) {
        var $this = $this,
            that = this,
            typename = $this.attr('name'),
            $next = $this.parent().next().next();
        if (typename == 'userEmail') {
            that.flag.userTel = false;
            $next.html('<span class="tip_msg">'+msg+'</span>');
            $next.children('.tip_msg').delay(2000).fadeOut(20000, function() {
               $(this).remove();
            });
        }
    }
}
$(function() {
	BSTYUN.emailBound.init();
});

/**
 * 返回安全信息页面
 */
function returnSafePage(){
	window.location.href="/user/userCenter/memberSafetyInfo";
}
